package main

// 导入gin包
import (
	"backend/controllers"
	"backend/database"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

var _db *gorm.DB

func Item(c *gin.Context) {
	id := c.Param("id")
	result := database.QueryItem(_db, id)
	c.JSON(200, result)
}

func Category(c *gin.Context) {
	result := database.QueryCategory(_db)
	c.JSON(200, result)
}

func Price(c *gin.Context) {
	price := c.Param("price")
	result := database.QueryPrice(_db, price)
	c.JSON(200, result)
}

func GetFood(c *gin.Context) {
	// /food?id=1234&name=Manu&value=111
	a := c.Query("value")
	b := c.DefaultQuery("price", "123")
	fmt.Println(a)
	fmt.Println(b)
	//
}

func Index(c *gin.Context) {
	// 查询最新发布的物品，按id倒序，取前20条
	keyword := c.Query("q")
	var items []database.Item
	if keyword != "" {
		items = database.SearchItems(_db, keyword)
	} else {
		_db.Order("id desc").Limit(20).Find(&items)
	}
	categories := database.QueryCategory(_db)
	// 构建分类id到名称的映射
	catMap := map[int64]string{}
	for _, cat := range categories {
		catMap[cat.ID] = cat.Category
	}
	c.HTML(http.StatusOK, "index.html", gin.H{
		"items":  items,
		"catMap": catMap,
	})
}
func Insert(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.JSON(401, gin.H{"error": "未登录"})
		return
	}
	title := c.PostForm("title")
	price := c.PostForm("price")
	category := c.PostForm("category")
	detail := c.PostForm("detail")
	int_category, _ := strconv.Atoi(category)

	// 处理图片上传
	file, err := c.FormFile("image")
	var imagePath string
	if err == nil && file != nil {
		uploadDir := "./static/upload/"
		_ = os.MkdirAll(uploadDir, os.ModePerm)
		filename := fmt.Sprintf("%d_%s", time.Now().UnixNano(), filepath.Base(file.Filename))
		savePath := filepath.Join(uploadDir, filename)
		imagePath = "/static/upload/" + filename
		if err := c.SaveUploadedFile(file, savePath); err != nil {
			c.JSON(500, gin.H{"error": "图片保存失败"})
			return
		}
	}

	item := database.Item{
		Title:    title,
		Price:    price,
		Category: int64(int_category),
		Detail:   detail,
		UserID:   userID,
		Image:    imagePath, // 保存图片路径
	}
	database.Insert(_db, item)
	c.JSON(200, gin.H{"success": true})
}

func AddPage(c *gin.Context) {
	categories := database.QueryCategory(_db)
	c.HTML(http.StatusOK, "add.html", gin.H{"categories": categories})
}

func UserCenter(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.Redirect(302, "/login")
		return
	}

	var user database.User
	if err := _db.Where("id = ?", userID).First(&user).Error; err != nil {
		c.String(http.StatusInternalServerError, "用户不存在")
		return
	}

	var userStatues database.User_statues
	if err := _db.Where("user_id = ?", userID).First(&userStatues).Error; err != nil && err != gorm.ErrRecordNotFound {
		c.String(http.StatusInternalServerError, "用户资料查询失败")
		return
	}

	avatarURL := ptrToStr(userStatues.UserImg)

	c.HTML(http.StatusOK, "user_center.html", gin.H{
		"username":  user.Username,
		"email":     user.Email,
		"avatarURL": avatarURL,
	})
}

func SearchPage(c *gin.Context) {
	keyword := c.Query("q")
	var items []database.Item
	if keyword != "" {
		items = database.SearchItems(_db, keyword)
	} else {
		items = []database.Item{}
	}
	c.HTML(http.StatusOK, "search.html", gin.H{"items": items})
}

func EditItemPage(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.Redirect(302, "/login")
		return
	}
	idStr := c.Param("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	item, err := database.GetItemByID(_db, id, userID)
	if err != nil {
		c.String(404, "物品不存在")
		return
	}
	categories := database.QueryCategory(_db)
	c.HTML(http.StatusOK, "add.html", gin.H{"edit": true, "item": item, "categories": categories})
}

func EditItemPost(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		// 只返回JSON，不跳转
		c.JSON(401, gin.H{"success": false, "error": "未登录"})
		return
	}
	idStr := c.Param("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	title := c.PostForm("title")
	price := c.PostForm("price")
	category := c.PostForm("category")
	detail := c.PostForm("detail")
	int_category, _ := strconv.Atoi(category)

	// 查询原商品
	item, err := database.GetItemByID(_db, id, userID)
	if err != nil {
		c.JSON(404, gin.H{"success": false, "error": "物品不存在"})
		return
	}

	// 处理图片删除
	deleteImage := c.PostForm("delete_image")
	if deleteImage == "1" && item.Image != "" {
		// 删除服务器上的图片文件
		imgPath := "." + item.Image
		_ = os.Remove(imgPath)
		item.Image = ""
	}

	// 处理图片上传（可选）
	file, err := c.FormFile("image")
	var imagePath string
	if err == nil && file != nil {
		uploadDir := "./static/upload/"
		_ = os.MkdirAll(uploadDir, os.ModePerm)
		filename := fmt.Sprintf("%d_%s", time.Now().UnixNano(), filepath.Base(file.Filename))
		savePath := filepath.Join(uploadDir, filename)
		imagePath = "/static/upload/" + filename
		if err := c.SaveUploadedFile(file, savePath); err != nil {
			c.JSON(500, gin.H{"success": false, "error": "图片保存失败"})
			return
		}
		// 如果原来有图片，删除原图片
		if item.Image != "" {
			_ = os.Remove("." + item.Image)
		}
		item.Image = imagePath
	}

	item.Title = title
	item.Price = price
	item.Category = int64(int_category)
	item.Detail = detail

	if err := _db.Save(&item).Error; err != nil {
		c.JSON(500, gin.H{"success": false, "error": "更新失败"})
		return
	}
	c.JSON(200, gin.H{"success": true})
}

func DeleteItem(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.Redirect(302, "/login")
		return
	}
	idStr := c.Param("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	err := database.DeleteItemByID(_db, id, userID)
	if err != nil {
		c.String(500, "删除失败")
		return
	}
	c.Redirect(302, "/user/center")
}

func MyItemsPage(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.Redirect(302, "/login")
		return
	}
	items := database.QueryItemsByUser(_db, userID)
	c.HTML(http.StatusOK, "item.html", gin.H{"items": items})
}
func ProfileEdit(c *gin.Context) {
	c.HTML(http.StatusOK, "profile_edit.html", gin.H{
		// "User": user,
	})
}
func ProfileEditPost(c *gin.Context) {
	session := sessions.Default(c)
	userID, okUserID := session.Get("user_id").(int64)
	username, okUsername := session.Get("username").(string)

	if !okUserID || !okUsername {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "未登录"})
		return
	}

	// 获取当前用户信息用于页面渲染
	var user database.User
	if err := _db.Where("id = ?", userID).First(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "用户不存在"})
		return
	}

	var userStatues database.User_statues
	if err := _db.Where("user_id = ?", userID).First(&userStatues).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			// 初始化新记录，继承 username
			userStatues = database.User_statues{
				UserID:   userID,
				Username: username,
			}
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "数据库查询失败"})
			return
		}
	}

	// 接收表单字段
	bio := c.PostForm("bio")
	gender := c.PostForm("gender")
	birthday := c.PostForm("birthday")
	prefer := c.PostForm("like")
	university := c.PostForm("school")
	zhimaCredit := c.PostForm("zhima")

	// 更新字段
	userStatues.Intro = strToPtr(bio)
	userStatues.Gender = strToPtr(gender)
	userStatues.Birthday = strToPtr(birthday)
	userStatues.Prefer = strToPtr(prefer)
	userStatues.University = strToPtr(university)
	userStatues.Zhima_Credit = strToPtr(zhimaCredit)

	// 处理头像上传
	file, err := c.FormFile("avatar")
	if err == nil && file != nil {
		uploadDir := "./static/upload/"
		_ = os.MkdirAll(uploadDir, os.ModePerm)
		filename := fmt.Sprintf("%d_%s", time.Now().UnixNano(), filepath.Base(file.Filename))
		savePath := filepath.Join(uploadDir, filename)
		avatarURL := "/static/upload/" + filename

		// 删除旧头像（如果有）
		if userStatues.UserImg != nil && *userStatues.UserImg != "" {
			oldImagePath := "." + *userStatues.UserImg
			os.Remove(oldImagePath)
		}

		if err := c.SaveUploadedFile(file, savePath); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "头像保存失败"})
			return
		}

		userStatues.UserImg = strToPtr(avatarURL)
	}

	// 获取新昵称
	newUsername := c.PostForm("username")

	// 判断是否修改了昵称
	if newUsername != "" && newUsername != user.Username {
		var count int64
		_db.Model(&database.User{}).Where("username = ?", newUsername).Count(&count)
		if count > 0 {
			c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "该昵称已被使用"})
			return
		}

		tx := _db.Begin()
		defer func() {
			if r := recover(); r != nil {
				tx.Rollback()
			}
		}()

		// 更新 user 表中的 username
		if err := tx.Model(&user).Update("username", newUsername).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "更新用户名失败"})
			return
		}

		// 更新 user_statues 表中的 username 和其他字段
		updates := map[string]interface{}{
			"username":     newUsername,
			"intro":        userStatues.Intro,
			"gender":       userStatues.Gender,
			"birthday":     userStatues.Birthday,
			"prefer":       userStatues.Prefer,
			"university":   userStatues.University,
			"zhima_credit": userStatues.Zhima_Credit,
			"user_image":   userStatues.UserImg,
		}

		if userStatues.UserID == 0 {
			// 新建用户资料
			updates["user_id"] = userID
			if err := tx.Table("user_statues").Create(updates).Error; err != nil {
				tx.Rollback()
				c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "创建用户状态失败"})
				return
			}
		} else {
			// 更新用户资料
			if err := tx.Table("user_statues").Where("user_id = ?", userID).Updates(updates).Error; err != nil {
				tx.Rollback()
				c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "更新资料表失败"})
				return
			}
		}

		// 更新 user 表中的 username
		if err := tx.Model(&user).Update("username", newUsername).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "更新用户名失败"})
			return
		}

		tx.Commit()

		// 更新 session
		session.Set("username", newUsername)
		_ = session.Save()
	} else {
		// 未修改昵称，直接更新 user_statues 表
		updates := map[string]interface{}{
			"intro":        userStatues.Intro,
			"gender":       userStatues.Gender,
			"birthday":     userStatues.Birthday,
			"prefer":       userStatues.Prefer,
			"university":   userStatues.University,
			"zhima_credit": userStatues.Zhima_Credit,
			"user_image":   userStatues.UserImg,
		}

		if userStatues.UserID == 0 {
			// 新增用户资料
			updates["username"] = user.Username
			updates["user_id"] = userID
			if err := _db.Table("user_statues").Create(updates).Error; err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "创建用户状态失败"})
				return
			}
		} else {
			// 更新用户资料
			if err := _db.Table("user_statues").Where("user_id = ?", userID).Updates(updates).Error; err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "更新用户状态失败"})
				return
			}
		}
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{"success": true})

}
func strToPtr(s string) *string {
	if s == "" {
		return nil
	}
	return &s
}
func UserProfile(c *gin.Context) {
	session := sessions.Default(c)
	userID, okUserID := session.Get("user_id").(int64)
	username, okUsername := session.Get("username").(string)

	if !okUserID || !okUsername {
		c.Redirect(http.StatusFound, "/login")
		return
	}

	var user database.User
	if err := _db.Where("id = ?", userID).First(&user).Error; err != nil {
		c.String(http.StatusInternalServerError, "用户不存在")
		return
	}

	var userStatues database.User_statues
	if err := _db.Where("user_id = ?", userID).First(&userStatues).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			// 如果没有资料记录，初始化默认值
			userStatues = database.User_statues{
				UserID:   userID,
				Username: username,
			}
		} else {
			c.String(http.StatusInternalServerError, "数据库查询失败")
			return
		}
	}

	// 构造数据传给模板
	data := gin.H{
		"User": struct {
			ID       int64
			Username string
			Bio      string
			Gender   string
			Birthday string
			Like     string
			School   string
			Zhima    string
			Avatar   string
		}{
			ID:       user.ID,
			Username: user.Username,
			Bio:      ptrToStr(userStatues.Intro),
			Gender:   ptrToStr(userStatues.Gender),
			Birthday: ptrToStr(userStatues.Birthday),
			Like:     ptrToStr(userStatues.Prefer),
			School:   ptrToStr(userStatues.University),
			Zhima:    ptrToStr(userStatues.Zhima_Credit),
			Avatar:   ptrToStr(userStatues.UserImg),
		},
	}

	c.HTML(http.StatusOK, "profile.html", data)
}

// 辅助函数：*string -> string
func ptrToStr(s *string) string {
	if s == nil {
		return ""
	}
	return *s
}

func cartHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "cart.html", nil)
}
func ChatHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "chat.html", nil)
}
func EndHandler(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.Redirect(302, "/login")
		return
	}

	itemIDsStr := c.Query("items")
	if itemIDsStr == "" {
		c.String(400, "未选择商品")
		return
	}

	// 解析商品 ID
	itemIDs := strings.Split(itemIDsStr, ",")
	var items []database.Item
	for _, idStr := range itemIDs {
		id, _ := strconv.ParseInt(idStr, 10, 64)
		var item database.Item
		if err := _db.Where("id = ?", id).First(&item).Error; err != nil {
			continue
		}
		items = append(items, item)
	}

	// 渲染模板并传入商品列表
	c.HTML(http.StatusOK, "end.html", gin.H{
		"items":  items,
		"userID": userID,
	})
}

func ItemDetail(c *gin.Context) {
	id := c.Param("id")
	var item database.Item
	err := _db.Where("id = ?", id).First(&item).Error
	if err != nil {
		c.String(http.StatusNotFound, "商品不存在")
		return
	}

	// 查询分类 map
	var categories []database.Category
	_db.Find(&categories)
	catMap := make(map[int64]string)
	for _, cat := range categories {
		catMap[cat.ID] = cat.Category
	}

	// 查询发布者信息（user 表）
	var user database.User
	err = _db.Where("id = ?", item.UserID).First(&user).Error
	if err != nil {
		c.String(http.StatusNotFound, "用户不存在")
		return
	}

	// 查询用户状态信息（user_statues 表）
	var userStatues database.User_statues
	err = _db.Where("user_id = ?", item.UserID).First(&userStatues).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		c.String(http.StatusInternalServerError, "用户资料查询失败")
		return
	}

	// 构造用户资料数据（排除 user_id 字段）
	userInfo := struct {
		Username    string
		Email       string
		UserImg     string
		Intro       string
		Gender      string
		Birthday    string
		Prefer      string
		University  string
		ZhimaCredit string
	}{
		Username:    user.Username,
		Email:       user.Email,
		UserImg:     ptrToStr(userStatues.UserImg),
		Intro:       ptrToStr(userStatues.Intro),
		Gender:      ptrToStr(userStatues.Gender),
		Birthday:    ptrToStr(userStatues.Birthday),
		Prefer:      ptrToStr(userStatues.Prefer),
		University:  ptrToStr(userStatues.University),
		ZhimaCredit: ptrToStr(userStatues.Zhima_Credit),
	}

	// 渲染模板
	c.HTML(http.StatusOK, "item_detail.html", gin.H{
		"item":   item,
		"catMap": catMap,
		"user":   userInfo,
	})
}
func AddToCart(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.JSON(401, gin.H{"error": "未登录"})
		return
	}

	itemIDStr := c.PostForm("itemId")
	quantityStr := c.PostForm("quantity")

	// 转换数值类型
	itemID, err := strconv.ParseInt(itemIDStr, 10, 64)
	if err != nil || itemID <= 0 {
		c.JSON(400, gin.H{"error": "请输入有效的商品 ID"})
		return
	}

	quantity, err := strconv.ParseInt(quantityStr, 10, 64)
	if err != nil || quantity <= 0 {
		c.JSON(400, gin.H{"error": "请输入有效的数量"})
		return
	}

	// 构造 cart 记录
	cartRecord := database.Cart{
		UserID:   userID,
		ItemID:   itemID,
		Quantity: int(quantity),
		AddTime:  time.Now(),
	}

	// 检查该用户是否已经添加过该商品
	var existing database.Cart
	result := _db.Where("user_id = ? AND item_id = ?", userID, itemID).First(&existing)
	if result.Error == nil {
		// 如果存在，更新数量
		existing.Quantity += cartRecord.Quantity
		existing.AddTime = cartRecord.AddTime // 可选：更新时间
		if err := _db.Save(&existing).Error; err != nil {
			c.JSON(500, gin.H{"error": "更新购物车失败"})
			return
		}
	} else {
		// 否则新增一条记录
		if err := _db.Create(&cartRecord).Error; err != nil {
			c.JSON(500, gin.H{"error": "添加到购物车失败：" + err.Error()})
			return
		}
	}

	// 日志打印
	fmt.Printf("插入购物车记录: %+v\n", cartRecord)

	// 重定向到购物车页面
	c.Redirect(http.StatusFound, "/cart.html")
}

func GetItemsincart(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.JSON(401, gin.H{"error": "未登录"})
		return
	}

	var cartItems []struct {
		ID       int64
		ItemID   int64
		Title    string
		Price    string
		Image    string
		Type     string
		Shopname string
		Number   int
		Money    int64
	}

	// 联合查询 cart 和 item 表
	err := _db.Table("cart").
		Select("cart.id, cart.item_id as ItemID, cart.quantity as Number, item.title as Title, item.price as Price, item.category as Type, item.image as Image, user.username as Shopname, (cart.quantity * CAST(item.price AS SIGNED)) as Money").
		Joins("JOIN item ON cart.item_id = item.id").
		Joins("JOIN user ON item.user_id = user.id").
		Where("cart.user_id = ?", userID).
		Scan(&cartItems).Error

	if err != nil {
		c.JSON(500, gin.H{"error": "数据库查询失败：" + err.Error()})
		return
	}

	c.JSON(200, cartItems)
}

func ConfirmPayment(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.JSON(401, gin.H{"error": "未登录"})
		return
	}

	var req ConfirmRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": "参数解析失败：" + err.Error()})
		return
	}

	itemIDsStr := req.ItemIDs

	tx := _db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	for _, idStr := range itemIDsStr {
		id, err := strconv.ParseInt(idStr, 10, 64)
		if err != nil {
			tx.Rollback()
			c.JSON(400, gin.H{"error": "无效的商品 ID：" + idStr})
			return
		}

		var item database.Item
		if err := tx.Where("id = ?", id).First(&item).Error; err != nil {
			tx.Rollback()
			c.JSON(500, gin.H{"error": "查找商品失败：" + err.Error()})
			return
		}

		endRecord := database.End{
			UserID:       userID,
			Shopname:     item.Title,
			Type:         fmt.Sprintf("%d", item.Category),
			Number:       1,
			Money:        int64(1),
			Shoppingtime: time.Now().Format("2006-01-02 15:04:05"),
		}

		if err := tx.Create(&endRecord).Error; err != nil {
			tx.Rollback()
			c.JSON(500, gin.H{"error": "插入订单失败：" + err.Error()})
			return
		}

		if err := tx.Delete(&database.Item{}, id).Error; err != nil {
			tx.Rollback()
			c.JSON(500, gin.H{"error": "删除商品失败：" + err.Error()})
			return
		}
	}

	tx.Commit()
	c.Redirect(302, "/user/center")
}

func MyBought(c *gin.Context) {
	session := sessions.Default(c)
	userID, ok := session.Get("user_id").(int64)
	if !ok {
		c.Redirect(302, "/login")
		return
	}

	var orders []database.End
	_db.Where("user_id = ?", userID).Find(&orders)

	c.HTML(http.StatusOK, "end.html", gin.H{
		"orders": orders,
	})
}

type ConfirmRequest struct {
	ItemIDs []string `json:"item_ids"`
}

// 入口函数
func main() {
	gin.SetMode(gin.ReleaseMode)
	_db = database.GetDB()
	r := gin.Default()

	// 注册 session 中间件
	store := cookie.NewStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.Static("/static", "./static")
	// r.Static("/css", "./css")
	// r.Static("/js", "./js")

	// 公开路由
	r.GET("/login", controllers.Login)
	r.POST("/login", controllers.LoginPost)
	r.GET("/register", controllers.Register)
	r.POST("/register", controllers.RegisterPost)
	r.GET("/logout", controllers.Logout)

	r.SetTrustedProxies([]string{"127.0.0.1"})
	r.LoadHTMLGlob("templates/*")
	r.GET("/get/item/:id", Item)
	// /get/item?id=2%title=iPhone
	r.GET("/get/price/:price", Price)
	r.GET("/get/category", Category)
	r.GET("/get/food", GetFood)
	r.POST("/add/item", Insert)
	// localhost:8080/
	r.GET("/", Index)
	r.GET("/add", AddPage)
	r.GET("/user/center", UserCenter)
	r.GET("/search", SearchPage)
	r.GET("/edit/item/:id", EditItemPage)
	r.POST("/edit/item/:id", EditItemPost)
	r.POST("/delete/item/:id", DeleteItem)
	r.GET("/my/items", MyItemsPage)
	r.GET("/user/profile/edit", ProfileEdit)
	r.POST("/user/profile/edit_post", ProfileEditPost)
	r.GET("/user/profile", UserProfile)
	r.GET("/user/chat", ChatHandler)
	r.GET("/cart.html", cartHandler)
	r.GET("/my", UserCenter)
	r.GET("/end", EndHandler)
	r.GET("/item/detail/:id", ItemDetail)
	r.POST("/add_to_cart", AddToCart)
	r.GET("/get/cart_items", GetItemsincart)
	r.POST("/confirm_payment", ConfirmPayment)
	r.GET("/my/bought", MyBought)
	r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}

//func EndPost(c *gin.Context) {
//	session := sessions.Default(c)
//	userID, ok := session.Get("user_id").(int64)
//	if !ok {
//		c.JSON(401, gin.H{"error": "未登录"})
//		return
//	}
//
//	shopname := c.PostForm("shopname")
//	type_ := c.PostForm("type")
//	numberStr := c.PostForm("number")
//	moneyStr := c.PostForm("money")
//
//	// 验证必填字段
//	if shopname == "" || type_ == "" || numberStr == "" || moneyStr == "" {
//		c.JSON(400, gin.H{"error": "所有字段都是必填项"})
//		return
//	}
//
//	// 转换数值类型
//	number, err := strconv.ParseInt(numberStr, 10, 64)
//	if err != nil || number <= 0 {
//		c.JSON(400, gin.H{"error": "请输入有效的数量"})
//		return
//	}
//
//	money, err := strconv.ParseInt(moneyStr, 10, 64)
//	if err != nil || money < 0 {
//		c.JSON(400, gin.H{"error": "请输入有效的金额"})
//		return
//	}
//
//	// 使用当前时间作为 shoppingtime
//	now := time.Now().Format("2006-01-02 15:04:05")
//
//	// 创建 end 记录
//	endRecord := database.End{
//		UserID:       userID,
//		Shopname:     shopname,
//		Type:         type_,
//		Number:       number,
//		Money:        money,
//		Shoppingtime: now,
//	}
//
//	if err := _db.Create(&endRecord).Error; err != nil {
//		c.JSON(500, gin.H{"error": "数据保存失败"})
//		return
//	}
//
//	// 重定向到 end 页面
//	c.Redirect(302, "/end")
//}
